import { openDatabase } from '../db/init'
import { v4 as uuidv4 } from 'uuid'

/**
 * 标签服务类
 */
export class TagService {
  /**
   * 创建新标签
   * @param {string} videoId 视频ID
   * @param {Object} tagData 标签数据
   * @param {string} tagData.description 标签描述
   * @param {string} tagData.color 标签颜色
   * @param {number} tagData.startTime 开始时间
   * @param {number} tagData.endTime 结束时间
   * @returns {Promise<void>}
   */
  static async createTag(videoId, { description, color, startTime, endTime }) {
    const db = await openDatabase()
    
    const createTag = db.transaction(() => {
      // 插入或获取标签
      db.prepare(
        `INSERT OR IGNORE INTO tags (id, name, color)
         VALUES (?, ?, ?)`
      ).run(uuidv4(), description, color)

      const tag = db.prepare('SELECT id FROM tags WHERE name = ?').get(description)
      if (!tag) {
        throw new Error('标签创建失败')
      }

      // 插入标签段
      db.prepare(
        `INSERT INTO video_tag_segments 
         (id, video_id, tag_id, start_time, end_time, description)
         VALUES (?, ?, ?, ?, ?, ?)`
      ).run(uuidv4(), videoId, tag.id, startTime, endTime, description)
    })

    createTag()
  }

  /**
   * 更新标签
   * @param {string} tagId 标签ID
   * @param {Object} tagData 标签数据
   * @param {string} tagData.description 标签描述
   * @param {string} tagData.color 标签颜色
   * @returns {Promise<void>}
   */
  static async updateTag(tagId, { description, color }) {
    const db = await openDatabase()
    
    const updateTag = db.transaction(() => {
      const segment = db.prepare(
        'SELECT tag_id FROM video_tag_segments WHERE id = ?'
      ).get(tagId)

      if (!segment) {
        throw new Error('找不到标签段')
      }

      db.prepare(
        `UPDATE tags 
         SET name = ?, color = ?
         WHERE id = ?`
      ).run(description, color, segment.tag_id)

      db.prepare(
        `UPDATE video_tag_segments 
         SET description = ?
         WHERE id = ?`
      ).run(description, tagId)
    })

    updateTag()
  }

  /**
   * 删除标签
   * @param {string} tagId 标签ID
   * @returns {Promise<void>}
   */
  static async deleteTag(tagId) {
    const db = await openDatabase()
    db.prepare('DELETE FROM video_tag_segments WHERE id = ?').run(tagId)
  }
} 